import os
import json

# 仓库路径：
repoPrefix = "https://gitee.com/zinface/youwant.document/raw/master/"
# 临时：
# repoPrefix = "http://0.0.0.0:43965/"

# 文档输出目录
_out = "_out"

if not os.path.exists(_out):
    os.mkdir(_out)


# 对每个给定目录生成Document
def GenerateDocuments(docDir):
    # 相对目录的文档输出目录
    _output = os.path.join(_out, docDir)

    # 列出目录下的所有文件, 组织文件路径
    fileNames = os.listdir(docDir)
    filePaths = [os.path.join(docDir, i) for i in fileNames if ".txt" in i]

    _documents = []
    for path in filePaths:
        with open(path, 'r') as file:
            # 文件名称
            _name = os.path.basename(path)
            # 文件头名称
            _file_head_name = ".".join(_name.split('.')[0:-1]) + "_head.txt"
            # 文件体名称
            _file_body_name = ".".join(_name.split('.')[0:-1]) + "_body.txt"

            # 组织对象
            _document = {}
            _document["name"] = _name
            _document["url"] = os.path.join(os.path.join(repoPrefix, _output), _file_body_name)
            filecontent = "".join(file.readlines())
            file.close()

            header_end_index = filecontent.find('---', 15) + 3
            header = filecontent[:header_end_index].split("---")[1]
            header_strip = header.strip()
            
            body = filecontent[header_end_index+2:]
            # body_strip = body.strip()
            
            file = open(os.path.join(_output, _file_head_name),'w')
            file.write(filecontent[0:header_end_index])
            file.flush()
            file.close()
            
            file = open(os.path.join(_output, _file_body_name),'w')
            file.write(body)
            file.flush()
            file.close()


            print("Generating:", os.path.join(_output, _file_head_name))
            print("Generating:", os.path.join(_output, _file_body_name))

            header_attributes = ["title", "description", "author", "date"]
            header_tags = ""

            for part in header_strip.split("\n\n"):
                for line in part.split("\n"):

                    for item in header_attributes:
                        if line.startswith(item):
                            _document[item] = line.strip()[len(item +": "):]

                if part.startswith("tags"):
                    _document["tags"] = []
                    if "[]" in part:
                        continue
                    for line in part.split("\n"):
                        if line.strip().startswith("-"):
                            _document["tags"].append(" ".join(line.strip().split(" ")[1:]))
            # print(_document)
            _documents.append(_document)

    return _documents

if __name__ == "__main__":

    # 指定编译的文档
    # documentPrefixs = ["document-cmake"]
    documentPrefixs = [i for i in os.listdir(".") if i.startswith("document")]
    documents = []
    outJson = "documents.json"

    for docDir in documentPrefixs:
        if not os.path.isdir(docDir):
            continue
        
        if not os.path.exists(os.path.join(_out, docDir)):
            os.mkdir(os.path.join(_out, docDir))

        _documents = GenerateDocuments(docDir)
        for _document in _documents:
            documents.append(_document)

    # 生成 documents.json
    with open(outJson, "w") as jsonfile:
        jsonfile.write(json.dumps(documents, ensure_ascii=False))
        jsonfile.flush()
    print("Generating:", outJson)
